<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 :closable="false"(是否展示“X”号) show-icon(显示图标) -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col :span="8">
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 将标签页改为many -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="mini"
            type="primary"
            :disabled="isButtonDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template scope="scope">
                <!-- 动态参数的tag -->
                <el-tag
                  type="primary"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 可编辑的tag标签设计 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 将标签页改为only -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="mini"
            type="primary"
            :disabled="isButtonDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性渲染表格 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template scope="scope">
                <!-- 动态参数的tag -->
                <el-tag
                  type="primary"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 可编辑的tag标签设计 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 修改表单 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateList()
  },
  data() {
    return {
      cateList: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 级联选择器双向绑定的数据
      selectedKeys: [],
      // tabs双向绑定的数据,默认值是默认选择的页签
      activeName: 'many',
      // 动态参数的数据
      manyTabData: [],
      // 静态属性的数据
      onlyTabData: [],
      // 添加属性对话框显示标志
      addDialogVisible: false,

      //添加属性对话框绑定对象
      addForm: {
        attr_name: '',
      },
      //添加属性表单元素验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
      // 修改对话框显示
      editDialogVisible: false,
      // 修改的表单数据对象
      editForm: {
        attr_name: '',
        attr_id: 0,
      },
      // 修改表单元素验证规则
      editFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
      //控制新的tag显示文本框还是tag按钮
      inputVisible: false,
      //绑定文本框的对象
      inputValue: '',
    }
  },
  methods: {
    // 获取级联选择器中的数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      //将数据列表赋值给cateList
      this.cateList = res.data
      // //保存总数据条数
      // this.total = res.data.total
      // console.log(res.data)
    },
    // 级联选择器切换监听
    async handleChange() {
      this.getPramsData()
    },
    //tab页签点击处理函数
    handleTabClick() {
      // console.log(this.activeName)
      this.getPramsData()
    },
    // 获取参数的列表数据
    async getPramsData() {
      // console.log(this.selectedKeys);
      // 选中的不是第三级,取消选择
      if (this.selectedKeys.length < 3) {
        this.selectedKeys = []
        //清空表格
        this.manyTabData=[]
        this.onlyTabData=[]
        return
      }
      // 选中的是第三级
      // console.log(this.selectedKeys)
      // 根据所选参数分类和当前所在面板获取对应参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status != 200) return this.$message.error('获取参数错误')
      //  将属性拆分,这里需要防止对空字符串的拆分出包含一个元素的数组.
      res.data.forEach((item) => {
        item.attr_vals =
          item.attr_vals.length > 0 ? item.attr_vals.split(' ') : []
        // 控制文本框显示
        item.inputVisible = false
        // 文本框显示内容
        item.inputValue = ''
      })
      console.log(res.data)
      // 对获取数据列表判断后放入不同的数据对象中
      if (this.activeName == 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    //添加参数的对话框关闭事件监听
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数
    async addParams() {
      // //预验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: '',
          }
        )
        // console.log(res.data)
        if (res.meta.status !== 201)
          return this.$message.error('添加' + this.titleText + '数据失败')
        this.$message.success('添加' + this.titleText + '数据成功')
        this.addDialogVisible = false
        this.getPramsData()
      })
    },
    // 展示修改对话框
    async showEditDialog(attr_id) {
      // 获取属性id
      // console.log(id);
      // 根据属性id查询属性其他参数
      const { data: res } = await this.$http(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      )

      this.editForm.attr_name = res.data.attr_name
      this.editForm.attr_id = res.data.attr_id
      // 填入属性名称
      // this.editForm.attr_name=data.attr_name
      this.editDialogVisible = true
    },
    // 重置修改对话框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //点击按钮,编辑参数
    editParams() {
      // 表单预验证
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(this.cateId)
        // console.log(this.editForm.attr_id)
        if (!valid) return
        //请求服务器,修改参数
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        )
        // 如果失败
        if (res.meta.status != 200)
          return this.$message.error('修改参数错误:' + res.meta.msg)
        // 如果成功
        this.$message.success('更新成功')
        // 更新页面数据
        this.getPramsData()
        // 关闭对话框
        this.editDialogVisible = false
      })
    },
    // 根据id删除属性
    async removeParams(attr_id) {
      // 操作确认
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 用户取消了该操作
      if (confirmResult != 'confirm') return this.$message.info('已经取消删除')
      //  用户确认删除操作
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status != 200)
        return this.$message.error('删除参数失败:' + res.meta.msg)
      //  删除成功
      this.$message.success('删除参数成功')
      // 更新页面数据
      this.getPramsData()
      // 关闭对话框
      this.editDialogVisible = false
    },
    // 新tag文本框失去焦点或按下回车的监听函数
    async handleInputConfirm(row) {
      // console.log('close')
      if (row.inputValue.trim().length == 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 将新输入的文本加入数组中
      row.attr_vals.push(row.inputValue.trim())
      // 将input内容清空
      row.inputValue = ''
      // 关闭文本框,显示按钮
      row.inputVisible = false
      // 发起api请求,修改参数
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
       if(res.meta.status!=200) return this.$message.error('更新失败:'+res.meta.msg)
       this.$message.success("更新成功")
      //  this.getPramsData()
    },
    //tag按钮点击监听
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      //$nextTick:在页面上元素被重新渲染之后，调用回调函数的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag标签
    async   handleClose(index,row)
    {
      // 从数据中删除tag标签的内容
      row.attr_vals.splice(index,1)
        // 发起api请求,修改参数
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
         if(res.meta.status!=200) return this.$message.error('删除失败:'+res.meta.msg)
       this.$message.success("删除成功")
    }
  },
  computed: {
    isButtonDisabled() {
      if (this.selectedKeys.length < 3) return true
      return false
    },
    // 三级分类id
    cateId() {
      if (this.selectedKeys.length == 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    //动态计算对话框标题文本
    titleText() {
      if (this.activeName === 'many') return '动态参数'
      return '静态属性'
    },
  },
}
</script>

<style>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px !important;
}
</style>